<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理 -->
      <el-row class="btn_container">
        <!-- 点击出弹层 -->
        <el-button size="mini" type="primary" @click="showDialog = true">添加角色</el-button>
      </el-row>
      <!-- 表格组件 -->
      <!-- 使用v-loading绑定table组件 -->
      <el-table v-loading="loading" :data="list">
        <!-- 列信息 -->
        <el-table-column align="center" label="角色" prop="name">
          <template v-slot="{row}">
            <!-- 两种场景 -->
            <!-- 编辑的状态-未编辑状态 -->
            <span v-if="!row.isEdit">{{ row.name }}</span>
            <el-input v-else v-model="row.editRow.name" size="mini" placeholder="请输入角色名称" />
          </template>
        </el-table-column>

        <el-table-column align="center" label="启用" prop="state">
          <template v-slot="{ row }">
            <template v-if="!row.isEdit"> {{ row.state === 1 ? '已启用' : '未启用' }}</template>
            <el-switch v-else v-model="row.editRow.state" size="mini" :active-value="1" :inactive-value="0" />

          </template>
        </el-table-column>
        <el-table-column align="center" label="描述" prop="description">
          <template v-slot="{ row }">
            <span v-if="!row.isEdit">{{ row.description }}</span>
            <el-input v-else v-model="row.editRow.description" type="textarea" size="mini" :rows="3" placeholder="请输入角色描述" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-slot="{ row }">
            <template v-if="!row.isEdit">
              <el-button size="mini" type="text" @click="btuPermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="btnEditRow(row.id)">编辑</el-button>
              <el-popconfirm title="确定要删除该数据吗" @onConfirm="confirmDel(row.id)">
                <template #reference>
                  <el-button style="margin-left: 10px" size="mini" type="text">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
            <template v-else>
              <el-button size="mini" type="primary" @click="btnEditOK(row)">确定</el-button>
              <!-- 取消方法 -->
              <el-button size="mini" @click="row.isEdit = false">取消</el-button>

            </template>

          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-row style="height:80px" type="flex" justify="end" align="middle">
        <!-- 绑定分页信息 -->
        <el-pagination
          layout="prev, pager, next, jumper, total"
          :total="pageParams.total"
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          @current-change="changePage"
        />
        <!-- 1 -> 2 -->
      </el-row>
    </div>
    <!-- 放置弹层组件 -->
    <!-- 弹层绑定关闭 -->
    <el-dialog width="500px" title="新增角色" :visible.sync="showDialog" @close="btnCancel">
      <!-- 绑定表单校验和数据 -->
      <el-form ref="addRole" label-width="80px" :model="addForm" :rules="addRules">
        <el-form-item prop="name" label="角色名称">
          <el-input v-model="addForm.name" size="mini" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item prop="state" label="启用">
          <el-switch v-model="addForm.state" :inactive-value="0" :active-value="1" size="mini" />
        </el-form-item>
        <el-form-item prop="description" label="角色描述">
          <el-input v-model="addForm.description" size="mini" placeholder="请输入角色描述" />
        </el-form-item>
        <el-row type="flex" justify="center">
          <el-button size="mini" @click="btnCancel">取消</el-button>
          <el-button size="mini" type="primary" @click="btnOK">确定</el-button>
        </el-row>
      </el-form>
    </el-dialog>
    <!-- 放置权限弹层 -->
    <el-dialog
      :visible.sync="showPermissionDialog"
      title="分配权限"
      width="500px"
      @close="showPermissionDialog=false"
    >
      <!-- 放置权限数据 -->
      <el-tree
        ref="permissionTree"
        node-key="id"
        :data="permissionData"
        :props="{ label: 'name',children:'children' }"
        show-checkbox
        default-expand-all
        check-strictly
        :default-checked-keys="permIds"
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
          <el-button size="mini" type="primary" @click="btnAssignRole">确定</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { addRoleAPI, delRoleAPI, getRoleListAPI, updateRoleAPI, getRoleDetailAPI, assignRoleAPI } from '@/api'
import { getPermissionListAPI } from '@/api/permission'
import { transListToTreeData } from '@/utils'

export default {
  name: 'Role',
  // 定义分页信息
  data() {
    return {
      loading: false,
      list: [], // 数据驱动视图  对数据进行劫持 监听get/set => 监听到变化 => 反应到UI上
      pageParams: {
        total: 0,
        page: 1, // 默认请求第一页
        pagesize: 5 // 每页5条
      },
      // 声明变量控制弹层显示
      showDialog: false,
      // 声明数据和规则
      addRules: {
        name: [{ required: true, message: '角色名称不能为空' }],
        description: [{ required: true, message: '角色描述不能为空' }]
      },
      addForm: {
        name: '',
        description: '',
        state: 0

      },
      showPermissionDialog: false, //  弹层的显示
      permissionData: [], //  接收数据
      currentRoleId: null, // 记录点击角色id
      permIds: []
    }
  },
  created() {
    this.getRoleList()
  },
  // 在初始化时调用API赋值给数据
  methods: {
    // 确定方法
    async btnOK() {
      await this.$refs.addRole.validate()
      await addRoleAPI(this.addForm)
      this.$message.success('新增角色成功')
      this.btnCancel()
      this.getRoleList() // 重新获取数据
    },
    // 取消方法
    btnCancel() {
      this.showDialog = false
      this.$refs.addRole.resetFields()
    },
    // 初始化时将总数赋值
    async getRoleList() {
      this.loading = true
      const { rows, total } = await getRoleListAPI(this.pageParams)
      this.list = rows
      console.log(this.list)

      // 拿到了当前页的数据
      // 每个数据上添加一个是否编辑的状态 isEdit
      // 获取数据之后针对每个数据定义标识
      // 初始化时缓存数据
      this.list.forEach(item => {
        this.$set(item, 'isEdit', false) // 添加对于isEdit的响应式 => UI的更新
        // 设置响应式数据 拷贝
        // 可以针对目标对象添加的属性，添加响应式
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
      this.pageParams.total = total
      this.loading = false
    },
    // 页码改变事件(切换分页时。获取对应页码的数据)
    changePage(newPage) {
      this.pageParams.page = newPage // 赋值新页码
      this.getRoleList()
    },
    // 点击编辑的方法（更新缓存数据）
    btnEditRow(row) {
      row.isEdit = true
      // 当前最新的数据赋值给拷贝的数据
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
      console.log(row)
    },
    // 行内编辑的确定方法
    async  btnEditOK(row) {
      if (row.editRow.name && row.editRow.description) {
        await updateRoleAPI({
          id: row.id,
          ...row.editRow // 最新的数据
        })
        this.$message.success('角色更新成功') // 改的是后台更新成功
        Object.assign(row, { ...row.editRow, isEdit: false })
      } else {
        this.$message.warning('角色名称和描述不能为空')
      }
    },
    // 删除
    async confirmDel(id) {
      await delRoleAPI(id) // 删除的是后台数据
      this.$message.success('删除成功')
      if (this.list.length === 1) this.pageParams.page-- // 页码-1
      this.getRoleList()
    },
    // 弹层
    async btuPermission(id) {
      this.currentRoleId = id
      this.permissionData = transListToTreeData(await getPermissionListAPI(), 0)
      // 获取角色详情
      const { permIds } = await getRoleDetailAPI(id)
      this.permIds = permIds
      console.log(permIds)
      this.permissionData = transListToTreeData(await getPermissionListAPI(), 0)
      this.showPermissionDialog = true
    },
    // 点击确定时触发
    // 给角色分配权限
    async btnAssignRole() {
      // 获取当前树组件选中的key
      await assignRoleAPI({
        id: this.currentRoleId,
        permIds: this.$refs.permissionTree.getCheckedKeys()
      })
      this.$message.success('分配权限成功')
      this.showPermissionDialog = false
    }
  }
}
</script>
<style scoped>
.btn_container {
  padding: 10px 20px;
}
</style>
